﻿#include "historymanager.h"
#include<QDir>
#include<QJsonDocument>
#include<QJsonArray>
#include"historyitem.h"
#include<QUrl>

int HistoryManager::id;

HistoryManager::HistoryManager()
{
    qDebug()<<"default historymanager ctor";
}

HistoryManager::HistoryManager(QString name)
{
     qDebug()<<"HistoryManager ctor"<<"name:"<<name;
    file.setFileName(QDir::currentPath()+"/userfolder/"+name+"/history.json");
    if(!file.open(QIODevice::ReadWrite))
        qDebug()<<"open file failed";
    QJsonDocument jsonDoc=QJsonDocument::fromJson(file.read(file.size()));
    QJsonObject jsonObject=jsonDoc.object();
    id=jsonObject.value("id").toInt();
    QJsonArray items=jsonObject.value("history").toArray();
    for(auto item : items)
    {
        QJsonObject dataObject=item.toObject();
        qDebug()<<dataObject.value("title").toString();
        HistoryItem historyItem(dataObject.value("url").toString(),dataObject.value("title").toString(),
                                dataObject.value("iconUrl").toString(),QDateTime::fromString(dataObject.value("date").toString()),
                                dataObject.value("id").toInt());
        list.append(QVariant::fromValue(historyItem));
    }
}

HistoryManager::~HistoryManager()
{
    qDebug()<<"HistoryManager dtor";
    file.remove();
   QJsonObject jsonObject;
   QJsonArray arr;

   jsonObject.insert("id",HistoryManager::id);
   for(auto x :list)
   {
       QJsonObject dataObject;
       HistoryItem item=x.value<HistoryItem>();
       dataObject.insert("id",item.id());
       dataObject.insert("url", item.url());
       dataObject.insert("title",item.title());
       dataObject.insert("iconUrl",item.icon());
       dataObject.insert("date",item.time().toString());
       arr.push_back(dataObject);
   }
   jsonObject.insert("history",arr);
   QJsonDocument jsonDoc(jsonObject);

   if(!file.open(QIODevice::WriteOnly))
       qDebug()<<"open file failed";
   file.write(jsonDoc.toJson());
   file.close();
}

void HistoryManager::add(QString url, QString icon, QString title,QDateTime time)
{

    qDebug()<<"add";
    qDebug()<<url;
    qDebug()<<icon;
    qDebug()<<title;
    qDebug()<<time;
    HistoryItem historyItem(url,title,icon,time,id++);
    list.append(QVariant::fromValue(historyItem));
}

QVariantList HistoryManager::getHistoryItemList()
{
    return list;
}

void HistoryManager::remove(int id)
{
    qDebug()<<"C++ remove"<<id;
    for(auto &x:list)
    {
        HistoryItem item=x.value<HistoryItem>();
        if(item.id()==id)
        {
            list.removeOne(x);
            return;
        }
    }
}

void HistoryManager::removeAll()
{
    list.clear();
}
